package com.gyyx.plugins;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
//import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.text.format.DateUtils;
//import com.unity3d.player.UnityPlayer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by xuchang on 2019/12/4
 */
public class AndroidNotificator {
    private static NotificationManager sNotificationManager;

    private static final String ID_HIGH_CHANNEL = "channel_1_unity";
    private static final String NAME_HIGH_CHANNEL = "channel_1_name_unity";

    private static final String ID_LOW_CHANNEL = "channel_low_unity";
    private static final String NAME_LOW_CHANNEL = "channel_name_low_unity";

    public static final int ID_SHOW_NOTIFICATION = 1001;
    
    public static int m_nLastID = 0;

//    public static Context unityContext = (Context)UnityPlayer.currentActivity;

    public static void ShowNotification(String pAppName, String title, String content, 
    		int delayMillis, boolean loop, int queueNum, int type)
    {
        //Log.d("Get!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "此时已從Unity接收到參數！！！！！");
        //sendNotificationDelay(unityContext, title, content, pAppName, delayMillis, loop, queueNum, type);
    }

    public static void sendNotificationDelay(Context context, String title, String content, String ticker, int millis, Boolean loop, int queueNum, int type) {
        int delayMillis = millis;
        if (delayMillis < 0) {
            throw new IllegalArgumentException("The param: delayMillis < 0");
        }

        Intent intent = new Intent("UNITY_NOTIFICATOR");
        intent.putExtra("ticker", ticker);
        intent.putExtra("title", title);
        intent.putExtra("content", content);
        intent.setClass(context, UnityNotifyReceiver.class);
        //intent.addFlags(0x01000000);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int)System.currentTimeMillis() , intent, PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Calendar calendar = Calendar.getInstance();
        
        if(type == 2)
        {
            calendar.add(Calendar.SECOND, delayMillis);
        }
        else
        {    
            calendar.set(Calendar.HOUR_OF_DAY, delayMillis);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
        }
        
        long alarmTime = calendar.getTimeInMillis(); 

        if (loop) {
            am.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, DateUtils.DAY_IN_MILLIS + delayMillis, pendingIntent);
        } else {
            am.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
        }
        
        //Log.d("Set!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "此时已設置時間！！！！！");
        //Toast.makeText(unityContext, "+++++++++++++++", Toast.LENGTH_SHORT).show();
    }

    public static void setInfoNotification(Context context, CharSequence title, CharSequence content, CharSequence ticker, PendingIntent pendingIntent) {
        Notification.Builder builder;
        
        ApplicationInfo applicationInfo = null;
        PackageManager pm = context.getPackageManager();
        
        try {
            applicationInfo = pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
        } catch (Exception ex) {
            ex.printStackTrace();
            return;
        }
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder = new Notification.Builder(context, ID_HIGH_CHANNEL);
        } else {
            builder = new Notification.Builder(context);
        }
        builder.setSmallIcon(applicationInfo.icon)
                .setContentTitle(title)
                .setContentText(content)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setProgress(0, 0, false);
        
         
        if (!TextUtils.isEmpty(ticker)) {
            builder.setTicker(ticker);
        }
        
        if (pendingIntent != null) {
            builder.setContentIntent(pendingIntent);
        } else {
            builder.setContentIntent(PendingIntent.getBroadcast(context, m_nLastID, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT));
        }
        NotificationManager manager = createNotificationManager(context);
//        manager.notify(m_nLastID++, builder.build());
        //Log.d("Send!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "此时已發送消息！！！！！");
        //Toast.makeText(unityContext, "-----------------------", Toast.LENGTH_SHORT).show();
    }

    private static NotificationManager createNotificationManager(Context context) {
        if (sNotificationManager != null) {
            return sNotificationManager;
        } 
        sNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationHightChannel = new NotificationChannel(ID_HIGH_CHANNEL, NAME_HIGH_CHANNEL, NotificationManager.IMPORTANCE_HIGH);
            NotificationChannel notificationLowChannel = new NotificationChannel(ID_LOW_CHANNEL, NAME_LOW_CHANNEL, NotificationManager.IMPORTANCE_LOW);
            notificationHightChannel.enableLights(true); //是否在桌面icon右上角展示小红点
            notificationHightChannel.setLightColor(Color.RED);
            
            notificationLowChannel.enableLights(true); //是否在桌面icon右上角展示小红点
            notificationLowChannel.setLightColor(Color.RED);
            List<NotificationChannel> channelList = new ArrayList<NotificationChannel>();
            channelList.add(notificationLowChannel);
            channelList.add(notificationHightChannel);
            sNotificationManager.createNotificationChannels(channelList);
        }
        //Log.d("SetChannel!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "此时已設置消息通道！！！！！");
        //Toast.makeText(unityContext, "**********************", Toast.LENGTH_SHORT).show();
        return sNotificationManager;
    }
    
    /**
     * 清除所有通知，包括日常通知
     */
    public static void ClearNotification() {
//        Activity act = UnityPlayer.currentActivity;
//        if(act != null)
//        {
//            NotificationManager nManager = (NotificationManager)act.getSystemService(Context.NOTIFICATION_SERVICE);
//            for(int i = m_nLastID; i >= 0; i--) {
//            	nManager.cancel(i);
//            }
//    		m_nLastID = 0;
//        }
		//Log.d("Clean!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "此时已清空广播消息");
		//Toast.makeText(unityContext, "Cleaning！！！！", Toast.LENGTH_SHORT).show();
    }
}
